<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getGoodsList, batchUpdateGoodsStatus, getGoodsCategoryList } from '@/api/goods'
import { watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formatTime } from '@/utils'
// 查询表单
const form = ref({
  code: '', // 商品编码
  category_id: '', // 商品分类
  name: '', // 商品名称
  status: '', // 商品状态
  start_time: '', // 开始时间
  end_time: '', // 结束时间
  page: 1,
  page_size: 10,
})

// 日期区间中转
const dateRange = ref([])

// 监听dateRange变化同步到form
watch(dateRange, (val) => {
  form.value.start_time = val && val.length > 0 ? val[0] : ''
  form.value.end_time = val && val.length > 1 ? val[1] : ''
})

const router = useRouter()
const tableData = ref([])
const tableLoading = ref(false)
const total = ref(0)
const selectedRows = ref([])
const tableRef = ref()

// 查询商品列表
const fetchGoodsList = async () => {
  tableLoading.value = true
  try {
    const params = {
      ...form.value,
      start_time: createTime.value && createTime.value.length > 0 ? createTime.value[0] : '',
      end_time: createTime.value && createTime.value.length > 1 ? createTime.value[1] : '',
    }
    const res = await getGoodsList(params)
    console.log(res)
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
  } finally {
    tableLoading.value = false
  }
}

// 查询按钮
const onSubmit = () => {
  form.value.page = 1
  selectedRows.value = [] // 清空选择
  fetchGoodsList()
}
// 重置按钮
const onReset = () => {
  form.value.code = ''
  form.value.category_id = ''
  form.value.name = ''
  form.value.status = ''
  form.value.start_time = ''
  form.value.end_time = ''
  form.value.page = 1
  form.value.page_size = 10
  selectedRows.value = [] // 清空选择
  createTime.value = ''
  fetchGoodsList()
}

// 分页
const handleSizeChange = (val: number) => {
  form.value.page_size = val
  selectedRows.value = [] // 清空选择
  fetchGoodsList()
}
const handleCurrentChange = (val: number) => {
  form.value.page = val
  selectedRows.value = [] // 清空选择
  fetchGoodsList()
}

const createTime = ref('')
const getTimeChange = (val) => {
  console.log(val, 'log')
}

// 批量上架/下架弹窗
const dialogBatchUp = ref(false)
const dialogBatchDown = ref(false)

// 是否有选中商品
const hasSelection = computed(() => selectedRows.value.length > 0)

// 表格选择变化处理
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  console.log('=== 表格选择变化 ===')
  console.log('选中的商品数量:', rows.length)
  console.log('选中的商品详情:', rows)
  if (rows.length > 0) {
    console.log(
      '选中的商品ID列表:',
      rows.map((item) => item.id),
    )
    console.log(
      '选中的商品名称列表:',
      rows.map((item) => item.name),
    )
  }
}

// 清空选择
const clearSelection = () => {
  console.log('清空选择')
  selectedRows.value = []
  tableRef.value?.clearSelection()
  console.log('已清空选择')
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectedRows.value.length === tableData.value.length) {
    // 如果已全选，则取消全选
    console.log('取消全选')
    tableRef.value?.clearSelection()
  } else {
    // 如果未全选，则全选
    console.log(`全选 ${tableData.value.length} 个商品`)
    tableData.value.forEach((row) => {
      tableRef.value?.toggleRowSelection(row, true)
    })
  }
}

// 批量上架
const batchListing = () => {
  console.log('=== 点击批量上架 ===')
  console.log('选中的商品数量:', selectedRows.value.length)
  console.log('选中的商品详情:', selectedRows.value)
  dialogBatchUp.value = true
}

const confirmBatchListing = async () => {
  try {
    const ids = selectedRows.value.map((row: any) => row.id).join(',')
    console.log('=== 批量上架操作 ===')
    console.log('批量上架的商品ID:', ids)
    console.log('批量上架的商品数量:', selectedRows.value.length)
    console.log('批量上架的商品详情:', selectedRows.value)
    console.log('请求参数:', { id: ids, type: 1 })

    const res = await batchUpdateGoodsStatus({ id: ids, type: 1 })
    console.log('批量上架响应:', res)

    if (res.code === 200) {
      ElMessage.success(`批量上架成功，共处理 ${selectedRows.value.length} 个商品`)
      dialogBatchUp.value = false
      selectedRows.value = [] // 清空选中项
      fetchGoodsList()
    } else {
      ElMessage.error(`批量上架失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('批量上架失败:', error)
    ElMessage.error('批量上架失败')
  }
}

// 批量下架
const batchDelisting = () => {
  console.log('=== 点击批量下架 ===')
  console.log('选中的商品数量:', selectedRows.value.length)
  console.log('选中的商品详情:', selectedRows.value)
  dialogBatchDown.value = true
}

// 上架下架
const handleStatus = async (row) => {
  const status = row.status
  if (status === 1) {
    // 下架
    const res = await batchUpdateGoodsStatus({ id: row.id.toString(), type: 2 })
    console.log(res, 'res')
    if (res.code === 200) {
      ElMessage.success('下架成功')
      fetchGoodsList()
    }
  } else if (status === 2) {
    // 上架
    const res = await batchUpdateGoodsStatus({ id: row.id.toString(), type: 1 })
    console.log(res, 'res')
    if (res.code === 200) {
      ElMessage.success('上架成功')
      fetchGoodsList()
    }
  }
}

const confirmBatchDelisting = async () => {
  try {
    const ids = selectedRows.value.map((row: any) => row.id).join(',')
    console.log('=== 批量下架操作 ===')
    console.log('批量下架的商品ID:', ids)
    console.log('批量下架的商品数量:', selectedRows.value.length)
    console.log('批量下架的商品详情:', selectedRows.value)
    console.log('请求参数:', { id: ids, type: 2 })

    const res = await batchUpdateGoodsStatus({ id: ids, type: 2 })
    console.log('批量下架响应:', res)

    if (res.code === 200) {
      ElMessage.success(`批量下架成功，共处理 ${selectedRows.value.length} 个商品`)
      dialogBatchDown.value = false
      selectedRows.value = [] // 清空选中项
      fetchGoodsList()
    } else {
      ElMessage.error(`批量下架失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('批量下架失败:', error)
    ElMessage.error('批量下架失败')
  }
}

// 新增、查看、编辑跳转
const goAdd = () => {
  router.push({ name: 'goodsForm', query: { mode: 'add' } })
}
const goView = (row) => {
  router.push({ name: 'goodsForm', query: { mode: 'view', id: row.id }, params: row })
}
const goEdit = (row) => {
  router.push({ name: 'goodsForm', query: { mode: 'edit', id: row.id }, params: row })
}

// 商品状态显示
const statusText = (status) => {
  if (status === 1) return '上架'
  if (status === 2) return '下架'
  return '-'
}
const statusType = (status) => {
  if (status === 1) return 'success'
  if (status === 2) return 'danger'
  return 'info'
}

fetchGoodsList()
</script>
<template>
  <div>
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="商品编号:">
        <el-input v-model="form.code" placeholder="请输入商品编号" clearable style="width: 185px" />
      </el-form-item>
      <el-form-item label="商品分类:">
        <el-select
          v-model="form.category_id"
          placeholder="请选择商品分类"
          style="width: 185px"
          clearable
        >
          <el-option label="家电清洗" :value="1" />
          <el-option label="家电维修" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称:">
        <el-input v-model="form.name" placeholder="请输入商品名称" clearable style="width: 185px" />
      </el-form-item>
      <el-form-item label="商品状态:">
        <el-select v-model="form.status" placeholder="请选择商品状态" style="width: 185px">
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间:">
        <el-date-picker
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="请选择更新时间"
          style="width: 220px"
          @change="getTimeChange"
          v-model="createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onReset" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <div class="actions-btn">
      <el-button type="primary" @click="goAdd">新增</el-button>
      <el-button type="success" :disabled="!hasSelection" @click="batchListing">
        批量上架
        <!-- <span v-if="hasSelection" class="selection-count">({{ selectedRows.length }})</span> -->
      </el-button>
      <el-button type="danger" :disabled="!hasSelection" @click="batchDelisting">
        批量下架
        <!-- <span v-if="hasSelection" class="selection-count">({{ selectedRows.length }})</span> -->
      </el-button>
    </div>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="tableLoading"
      border
      style="width: 100%"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" fixed="left" />
      <el-table-column prop="code" label="商品编号" width="120" fixed="left">
        <template #default="{ row }">
          <el-button link type="primary" @click="goView(row)" class="code-link-btn">
            {{ row.code }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" />
      <el-table-column label="商品主图" width="100">
        <template #default="scope">
          <img
            v-if="scope.row.main_img"
            :src="`/api/${scope.row.main_img}`"
            class="goods-img"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="category_id" label="商品分类" width="120">
        <template #default="scope">
          <span>{{
            scope.row.category_id === 1
              ? '家电清洗'
              : scope.row.category_id === 2
                ? '家电维修'
                : '团购季'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sub_name" label="商品说明（副标题）" width="200" />
      <el-table-column label="商品状态" width="100">
        <template #default="scope">
          <el-button
            type="success"
            size="small"
            style="color: #70b603"
            @click="handleStatus(scope.row)"
            v-if="scope.row.status === 1"
            text
          >
            上架
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleStatus(scope.row)"
            text
            v-else-if="scope.row.status === 2"
          >
            下架
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="更新时间" width="180">
        <template #default="scope">
          <span>{{ scope.row.updated_at ? formatTime(scope.row.updated_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="更新说明" width="120" />
      <el-table-column prop="sold_count" label="售出数量" width="100">
        <template #default="scope">
          <span>{{ scope.row.historical_sold_count || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sold_amount" label="售出金额" width="100">
        <template #default="scope">
          <span>{{ scope.row.historical_sold_amount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="goView(scope.row)">查看</el-button>
          <el-button link type="primary" size="small" @click="goEdit(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="form.page_size"
        :current-page="form.page"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 批量上架弹窗 -->
    <el-dialog v-model="dialogBatchUp" title="操作提示" width="400">
      <div class="info">
        确认 <span>【批量上架】</span> 已选中的
        <span class="count">{{ selectedRows.length }}</span> 个商品吗？
      </div>
      <!-- <div class="selected-items" v-if="selectedRows.length > 0">
        <div class="selected-title">选中的商品：</div>
        <div class="selected-list">
          <div v-for="item in selectedRows" :key="item.id" class="selected-item">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-code">({{ item.code }})</span>
            <span class="item-status" :class="item.status === 1 ? 'status-up' : 'status-down'">
              {{ item.status === 1 ? '已上架' : '已下架' }}
            </span>
          </div>
        </div>
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogBatchUp = false">关闭</el-button>
          <el-button type="primary" @click="confirmBatchListing"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量下架弹窗 -->
    <el-dialog v-model="dialogBatchDown" title="操作提示" width="400">
      <div class="info">
        确认 <span>【批量下架】</span> 已选中的
        <span class="count">{{ selectedRows.length }}</span> 个商品吗？
      </div>
      <!-- <div class="selected-items" v-if="selectedRows.length > 0">
        <div class="selected-title">选中的商品：</div>
        <div class="selected-list">
          <div v-for="item in selectedRows" :key="item.id" class="selected-item">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-code">({{ item.code }})</span>
            <span class="item-status" :class="item.status === 1 ? 'status-up' : 'status-down'">
              {{ item.status === 1 ? '已上架' : '已下架' }}
            </span>
          </div>
        </div>
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogBatchDown = false">关闭</el-button>
          <el-button type="danger" @click="confirmBatchDelisting"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.actions-btn {
  margin-bottom: 20px;
}

.selection-count {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.8;
}

.selection-status {
  margin-bottom: 15px;
}

.selection-preview {
  margin-top: 5px;
}

.preview-item {
  color: #409eff;
  font-weight: 500;
}

.more-text {
  color: #909399;
  font-size: 12px;
}
.pagination {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}
.tips {
  color: red;
  font-size: 12px;
}
.info span {
  color: #e6a23c;
}

.info .count {
  color: #409eff;
  font-weight: bold;
}

.selected-items {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.selected-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #606266;
}

.selected-list {
  max-height: 120px;
  overflow-y: auto;
}

.selected-item {
  padding: 4px 8px;
  margin-bottom: 4px;
  background: #fff;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-item:last-child {
  margin-bottom: 0;
}

.item-name {
  font-weight: 500;
  color: #303133;
}

.item-code {
  color: #909399;
}

.item-status {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 2px;
  margin-left: auto;
}

.status-up {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #b3e19d;
}

.status-down {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fab6b6;
}
.goods-img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  background: #f2f2f2;
}
</style>
